/**
 * @Description: 路由权限
 * @Author bianpengfei
 * @create 2022/11/24 20:33
 */
import useLayoutStore from '@store/use-layout-store'
import useMenuStore from '@store/use-menu-store'
import useUserStore from '@store/use-user-store'
import { $initDict } from '@/utils/dict'
import { $initParam } from '@/utils/param'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { whiteList, publicPaths } from '@/router/routes'
import profile from '@root/profile'
import { arrayToObj, cache } from 'sf-utils2'
import setting from '@/setting'
import { ElMessage } from 'element-plus'
import { error } from '@shared/utils/log'
import { QIANKUN_PLATFORM } from '@/utils/constants.ts'
import useAppStore from '@store/use-app-store.ts'

// types

NProgress.configure({ showSpinner: false })

/**
 * 获取子应用激活规则
 * @param path
 */
function getMicroAppActiveRule(path) {
  return ['/', path.split('/').filter(Boolean).at(0)].join('')
}

/**
 * 路由钩子鉴权
 */
export default function routerMiddlewareAuth() {
  const layoutStore = useLayoutStore()
  const userStore = useUserStore()
  const menuStore = useMenuStore()
  const appStore = useAppStore()

  // const tempRoutes = this.getRoutes()
  // console.log('tempRoutes', tempRoutes)

  const authComponentPathObj = arrayToObj(profile.authComponentPaths) // 需要权限的映射

  /**
   * 路由鉴权
   */
  this.beforeEach(async (to, from, next) => {
    try {
      // 在非乾坤中 显示加载进度条
      !window.__POWERED_BY_QIANKUN__ && NProgress.start()

      if (window.__POWERED_BY_QIANKUN__) {
        const microAppProps = appStore.microAppProps
        switch (microAppProps?.platform) {
          // 特资星
          case QIANKUN_PLATFORM.TZX: {
            break
          }

          // 法诉平台
          case QIANKUN_PLATFORM.BASE: {
            const pathName = window.location.pathname
            const activeRule = getMicroAppActiveRule(pathName)
            console.log('activeRule@', activeRule, microAppProps.registrableApp.activeRule)
            if (microAppProps.registrableApp.activeRule != activeRule) return
            break
          }
        }
      }

      if (to.__skip === true) return next()

      // 跳过权限校验，只做前端界面画
      if (setting.isSkipAuth) return next()

      const pendings = [] // 要请求的数据

      const { userInfo, token, departTree } = userStore
      const { authMenus } = menuStore

      // fix 如果用户信息存在，则不允许访问login页面
      if (token && ['/Login', '/login'].includes(to.path)) return next({ path: '/home' })

      // 白名单, 公共路由，不需要权限，放行
      if (whiteList.includes(to.path) || publicPaths.some((v) => !!v?.test(to.path)) || to.meta.auth === false) {
        return next()
      }

      // 判断是否有token
      if (!token) {
        if (['dev', 'sit', 'uat', 'prd'].includes(profile.APP_MODE)) {
          // 如果是sit环境，跳转到新核心的登录页面
          return (window.location.href = profile.newCoreAddress + '/login?systemId=cf-manage')
        } else {
          return next({ path: '/login', query: { redirect: to.fullPath } })
        }
      }

      if (token) {
        // 判断是否已经成功加载字典
        if (!cache?.getItem('DICT')) pendings.push($initDict())
        if (!cache?.getItem('PARAM')) pendings.push($initParam())
      }

      // 用户信息不存在，获取用户信息
      if (!userInfo?.id) pendings.push(userStore.getUserInfo())

      // 部门信息不存在
      if (!departTree?.length && !departTree?.__hasLoaded__) pendings.push(userStore.getUserDeparts())

      // 获取用户权限数据
      if (!authMenus?.length && !authMenus?.__hasLoaded__) pendings.push(menuStore.getUserAuthMenus())

      // 执行所有异步任务
      if (pendings.length) await layoutStore.load(Promise.all(pendings))

      // 跳过权限路由校验
      if (setting.isSkipRouterAuth) return next()

      // 放开权限，这期放开菜单权限
      // 判断是否有权限访问页面
      // console.log('appStore._authMenuList', appStore._authMenuList)
      if (authComponentPathObj[to.path] || to.meta?.auth === true) {
        const { hasPermission } = this.__AUTH_ROUTE_NEXT_TO__(to.fullPath)

        // // 如果没有权限，统一跳转到401 无权限访问页面
        if (!hasPermission) return next({ path: '/Error/Page401', replace: true })
      }

      // 最终放行
      next()
    } catch (e) {
      // 在非乾坤中 关闭加载进度条
      !window.__POWERED_BY_QIANKUN__ && NProgress.done()
      e && ElMessage.error(e.toString())
      error('[routesAuth.js]', e)
    }
  })

  this.afterEach(() => {
    // 在非乾坤中 关闭加载进度条
    !window.__POWERED_BY_QIANKUN__ && NProgress.done()
  })
}
